'use strict'

define(['jquery', 'bootstrap', 'select2', 'shiftform', 'validate', 'validate.en'], function($) {
  
  return {
        
    init: function() {
        this.create();
        this.delete();
    },
    
    create: function() {
      var that = this;
        $(document).on('shown.bs.modal', '#agent-create', function(e){
          
          that.bindUserSearchClick(e);
          
          var $percentageValidate = {'percentage_validate' : function(value) { return that.validatePercentage(value); }}
          $.extend($.bt_validate.fn, $percentageValidate)
          $.extend($.bt_validate.text, {'percentage_validate' : '请输入小于100%的数字!'})

        $(e.currentTarget).find('form[data-validate="true"]').bt_validate()  //bind validate
          
          var $form = $(e.currentTarget).find("form")                          //bind shiftform
          $form.shiftform({
            beforeSubmit : function(el) {
            $form.trigger("validate.ajax.submit");
              return $.bt_validate.result[$.bt_validate.form_id];
            }
          })
        })
      },
      
      validatePercentage: function(value) {
        var result = true;
        
      if(value != '') {
        var offers = value.split(',');
          for(var j=0; j<offers.length; j++) {
              if(offers[j] > 100){
                result = false;
              }
            }
      }
          return result;
      },
      
      bindUserSearchClick: function(e) {
        $(e.currentTarget).find('.user-search').click(function() {
          var mobile = $(e.currentTarget).find('input[name="mobile"]').val()
          if(mobile != '') {
            $.ajax({
                url: window.__CTX__.root + "/distributors/search-user",
                type: 'GET',
                data: {"filters": "true", "mobile": mobile},
                cache: false
              }).done(function(result) {
                result = JSON.parse(result);
                $(e.currentTarget).find('.search-block').css("display", "");
                if(result.code == '0') {
                  $(e.currentTarget).find('input[name="userId"]').val(result.data.userId);
                  $(e.currentTarget).find('.search-result').text(result.data.username);
                  $(e.currentTarget).find('.btn-success').removeClass("disabled")
                } else if(result.code == '1') {
                  $(e.currentTarget).find('.search-result').text(result.message);
                  $(e.currentTarget).find('.btn-success').addClass("disabled")
                }
              })
          }
           
        })
      },
      
      delete: function() {
        $(document).on('shown.bs.modal', '#agent-delete', function(e){
          $(e.currentTarget).find("form").shiftform()
        })
      }
  }
})
